package cn.zh.npro.Activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.zh.npro.Adapter.CeAdapter;
import cn.zh.npro.Adapter.CpAdapter;
import cn.zh.npro.Adapter.CrAdapter;
import cn.zh.npro.Adapter.CtAdapter;
import cn.zh.npro.Item.ClevItem;
import cn.zh.npro.Item.CpItem;
import cn.zh.npro.Item.CrItem;
import cn.zh.npro.Item.CtItem;
import cn.zh.npro.Item.GCItem;
import cn.zh.npro.MyApplication;
import cn.zh.npro.R;
import cn.zh.npro.Util.BaseUrl;
import cn.zh.npro.Util.Loading;
import cn.zh.npro.Util.ToastUtil;
import cn.zh.npro.citythreelist.ProvinceActivity;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class CliEdit extends BaseActivity {
   ImageView mc_back;
   TextView cecom;
   String cusId;
   EditText ecliname,edtadress;
   TextView cuslevel,custype,paytype;
   TextView cadress;
   LinearLayout clvelin,claslin,ptlin,adrelin;
   PopupWindow popupWindow;
    CeAdapter ceAdapter;
   ArrayList<ClevItem> clevItems=new ArrayList<>();
    CtAdapter ctAdapter;
   ArrayList<CtItem> ctItems=new ArrayList<>();
    CpAdapter cpAdapter;
    CrAdapter crAdapter;
    ArrayList<CpItem> cpItems=new ArrayList<>();
    ArrayList<CrItem> crItems=new ArrayList<>();
    int type=0;
    String customerLevel,customerType,ChargeType;
    ClevItem clevItem=null;
    CtItem ctItem=null;
    CpItem cpItem=null;
    CrItem crItem = null;
    MyApplication mapp;
    String provinceId="",cityId="",countyId="",provinceName="",cityName="",countyName="";
    String handle,handleName;
    private Dialog LDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cli_edit);
        cusId=getIntent().getStringExtra("cusId");
        mapp= (MyApplication) getApplication();
        initcf();
        }

    public void initcf(){
        mc_back=findViewById(R.id.mc_back);
        cecom=findViewById(R.id.cecom);
        ecliname=findViewById(R.id.ecliname);
        cuslevel=findViewById(R.id.cuslevel);
        custype=findViewById(R.id.custype);
        paytype=findViewById(R.id.paytype);
        cadress=findViewById(R.id.cadress);
        edtadress=findViewById(R.id.edtadress);

        clvelin=findViewById(R.id.clvelin);
        claslin=findViewById(R.id.claslin);
        ptlin=findViewById(R.id.ptlin);
        adrelin=findViewById(R.id.adrelin);

        mc_back.setOnClickListener(this);
        cecom.setOnClickListener(this);

        clvelin.setOnClickListener(this);
        claslin.setOnClickListener(this);
        ptlin.setOnClickListener(this);
        adrelin.setOnClickListener(this);
        }

    @Override
    protected void onResume() {
        super.onResume();

        if (mapp.isIscity()){
            provinceName=mapp.getProviece().getName();
            cityName=mapp.getCityitem().getName();
            countyName=mapp.getAreaim().getName();
            provinceId=mapp.getProviece().getId();
            cityId=mapp.getCityitem().getId();
            countyId=mapp.getAreaim().getId();
            cadress.setText(provinceName+"-"+cityName+"-"+countyName);
            mapp.setIscity(false);
         }else {
            getCdent();
        }
      }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id=view.getId();
        switch (id){
            case R.id.mc_back:
                finish();
                break;
            case R.id.clvelin:
                type=0;
                showPopUp();
                initcls();
                break;
            case R.id.claslin:
                type=1;
                showPopUp();
                getGetCustomerClass();
                break;
            case R.id.ptlin:
                type=2;
                showPopUp();
                Chatype();
                break;
            case R.id.adrelin:
                mapp.setArechose(0);
                //地址
                Intent intent=new Intent(CliEdit.this, ProvinceActivity.class);
                startActivity(intent);
                break;
            case R.id.cecom:
                //完成
                GetUpdateCustomer();
                break;
            }
         }


    //侧滑弹窗
    private void showPopUp() {
        View vp = LayoutInflater.from(CliEdit.this).inflate(R.layout.clv_layout, null, false);
        ListView lplist=vp.findViewById(R.id.plist);
        TextView ptitle=vp.findViewById(R.id.ptitle);
        switch (type){
            case 0:
                ptitle.setText("客户级别");
                String txt=cuslevel.getText().toString();
                ceAdapter = new CeAdapter(CliEdit.this,clevItems,txt);
                lplist.setAdapter(ceAdapter);
                break;
            case 1:
                ptitle.setText("客户分类");
                String txt1=custype.getText().toString();
                crAdapter = new CrAdapter(CliEdit.this,crItems,txt1);
                lplist.setAdapter(crAdapter);
                break;
            case 2:
                ptitle.setText("付款方式");
                String txt2=paytype.getText().toString();
                cpAdapter = new CpAdapter(CliEdit.this,cpItems,txt2);
                lplist.setAdapter(cpAdapter);
                break;
              }

        lplist.setOnItemClickListener(                      new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (type){
                    case 0:
                        popupWindow.dismiss();
                        cuslevel.setText(clevItems.get(i).getCustomerLevelTitle());
                        clevItem=clevItems.get(i);
                        break;
                    case 1:
                        popupWindow.dismiss();
                        custype.setText(crItems.get(i).getClassName());
                        crItem=crItems.get(i);
                        break;
                    case 2:
                        popupWindow.dismiss();
                        paytype.setText(cpItems.get(i).getChargeTypeName());
                        cpItem=cpItems.get(i);
                        break;
                 }
              }
          });

        WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        int  mScreenWitdh = outMetrics.widthPixels;
        popupWindow = new PopupWindow(vp, mScreenWitdh-200, LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.GRAY));
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        popupWindow.setClippingEnabled(false);
        popupWindow.setAnimationStyle(R.style.popwin_anim_style);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        WindowManager.LayoutParams lp =getWindow().getAttributes();
        lp.alpha=0.5f;
        getWindow().setAttributes(lp);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp =getWindow().getAttributes();
                lp.alpha=1.0f;
                getWindow().setAttributes(lp);
                 }
        });
        popupWindow.showAtLocation(findViewById(R.id.cliedt_layout), Gravity.NO_GRAVITY, 200, 0);

        }






    public void getCdent(){
        OkHttpUtils.get(BaseUrl.GetCustomerDetail)
                .params("customerId",cusId)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                JSONObject Res=js.getJSONObject("Res");
                                JSONObject Customer=Res.getJSONObject("Customer");
                                String id=Customer.getString("ID");
                                String companyName=Customer.getString("companyName");
                                customerType = Customer.getString("customerType");
                                customerLevel = Customer.getString("CustomerLevel");
                                ChargeType = Customer.getString("ChargeType");
                                String address=Customer.getString("address");
                                String joinDate=Customer.getString("joinDate");
                                String province=Customer.getString("province");
                                String provinId=Customer.getString("provinceId");
                                String city=Customer.getString("city");
                                String ciId=Customer.getString("cityId");
                                String county=Customer.getString("county");
                                String couyId=Customer.getString("countyId");
                                handle = Customer.getString("handle");
                                handleName=Customer.getString("handleName");
                                ecliname.setText(companyName);
                                cuslevel.setText(customerLevel);
                                custype.setText(customerType);
                                paytype.setText(ChargeType);
                                edtadress.setText(address);
                                cadress.setText(province+"-"+city+"-"+county);
                                provinceName=province;
                                cityName=city;
                                countyName=county;
                                provinceId=provinId;
                                cityId=ciId;
                                countyId=couyId;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
           }





      public void initcls(){
        OkHttpUtils.get(BaseUrl.GetCustomerLevel)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                JSONArray Res=js.getJSONArray("Res");
                                clevItems.clear();
                                for (int i=0;i<Res.length();i++){
                                     JSONObject ji=Res.getJSONObject(i);
                                     String customerLevelId=ji.getString("customerLevelId");
                                     String customerLevel=ji.getString("customerLevel");
                                     String customerLevelTitle=ji.getString("customerLevelTitle");
                                     String days=ji.getString("days");
                                     String sortOrder=ji.getString("sortOrder");
                                    ClevItem clevItem=new ClevItem(customerLevelId,customerLevel,customerLevelTitle,days,sortOrder);
                                    clevItems.add(clevItem);
                                  }
                                ceAdapter.notifyDataSetChanged();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
              }



    public void getGetCustomerClass(){
        OkHttpUtils.get(BaseUrl.GetCustomerClass)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                JSONArray Res=js.getJSONArray("Res");
                                crItems.clear();
                                for (int i=0;i<Res.length();i++){
                                    JSONObject ji=Res.getJSONObject(i);
                                    String ClassID=ji.getString("ClassID");
                                    String ClassName=ji.getString("ClassName");
                                    String OrderPos=ji.getString("OrderPos");
                                    String bBlockUp=ji.getString("bBlockUp");
                                    CrItem crItem= new CrItem(ClassID,ClassName,OrderPos,bBlockUp);
                                    crItems.add(crItem);
                                }
                                crAdapter.notifyDataSetChanged();

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
    }


    public void Chatype(){
             OkHttpUtils.get(BaseUrl.GetChargeType)
                     .execute(new StringCallback() {
                         @Override
                         public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                             try {
                                 JSONObject js=new JSONObject(s);
                                 boolean State=js.getBoolean("State");
                                 JSONArray Res=js.getJSONArray("Res");
                                 cpItems.clear();
                                 for (int i=0;i<Res.length();i++){
                                   JSONObject ji=Res.getJSONObject(i);
                                   String ChargeTypeID=ji.getString("ChargeTypeID");
                                   String ChargeTypeName=ji.getString("ChargeTypeName");
                                   String OrderPos=ji.getString("OrderPos");
                                   String bBlockUp=ji.getString("bBlockUp");
                                   CpItem cpItem=new CpItem(ChargeTypeID,ChargeTypeName,OrderPos,bBlockUp);
                                   cpItems.add(cpItem);
                                 }
                                 cpAdapter.notifyDataSetChanged();

                             } catch (JSONException e) {
                                 e.printStackTrace();
                             }
                         }
                         @Override
                         public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                             super.onError(isFromCache, call, response, e);
                         }
                     });
                    }


            public void GetUpdateCustomer(){
                String name=ecliname.getText().toString();
                String dadre=edtadress.getText().toString();
                String cust=custype.getText().toString();
                String clev=cuslevel.getText().toString();
                String patxt=paytype.getText().toString();
                if (name.equals("")){
                    ToastUtil.showLong(CliEdit.this,"客户名称未填写");
                    return;
                }
                if (clev.equals("")){
                    ToastUtil.showLong(CliEdit.this,"请设置客户级别");
                    return;
                }
                if (cust.equals("")){
                    ToastUtil.showLong(CliEdit.this,"请设置客户分类");
                    return;
                }
                if (patxt.equals("")){
                    ToastUtil.showLong(CliEdit.this,"请设置付款方式");
                    return;
                }

                if (dadre.equals("")){
                    ToastUtil.showLong(CliEdit.this,"请填写详细地址");
                    return;
                 }

                LDialog= Loading.createLoadingDialog(this,"加载中...");
                Gson gson = new Gson();
                GCItem gcItem=new GCItem(cusId,handleName,provinceName,handle,countyId,dadre,cityName,name,countyName,provinceId,cust,cityId,clev,patxt);
                String str=gson.toJson(gcItem);
                 OkHttpUtils.post(BaseUrl.UpdateCustomer)
                         .postJson(str)
                         .execute(new StringCallback() {
                             @Override
                             public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                                 if (null!=LDialog){
                                     Loading.closeDialog(LDialog);
                                   }
                                 try {
                                     JSONObject js=new JSONObject(s);
                                     boolean State=js.getBoolean("State");
                                     String Msg=js.getString("Msg");
                                     if (State){
                                         ToastUtil.showLong(CliEdit.this,Msg);
                                         finish();
                                     }else {
                                         ToastUtil.showLong(CliEdit.this,Msg);
                                     }
                                 } catch (JSONException e) {
                                     e.printStackTrace();
                                 }
                             }
                             @Override
                             public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                                 super.onError(isFromCache, call, response, e);
                             }
                         });
               }

         }
